import express from "express";
import { Response, Request } from "express";
import { failure, success } from "../utils/responses";
import { getExampleFileDownloadUrl, upload, uploadExcel, uploadMiddleWare } from "../utils/qiniuyun";
import { BadRequest } from "http-errors";
import { AuthRequest } from "../middlewares/user-auth";
import { AppDataSource } from "../config/database";
import { Exam } from "../entities/Exam";

const router = express.Router();

/**
 * 图片上传
 */
router.post("/upload", uploadMiddleWare.single('file'), async function (req: Request, res: Response) {
  try {
    if (!req.file) return failure(res, new BadRequest('请选择要上传的文件'))
    const file = req.file // 获取上传的文件
    const filePath = file.path // 获取上传的文件的路径

    const data = await upload(filePath)
    console.log('data：' + JSON.stringify(data))
    success(res, '上传成功', data.imageUrl)
  } catch (error) {
    failure(res, error)
  }
})

/**
 * Excel上传
 */
router.post("/uploadExcel", uploadMiddleWare.single('file'), async function (req: Request, res: Response) {
  try {
    if (!req.file) return failure(res, new BadRequest('请选择要上传的文件'))
    const file = req.file // 获取上传的文件
    const filePath = file.path // 获取上传的文件的路径
    const userId = (req as AuthRequest).id

    const data = await uploadExcel(filePath, userId)
    console.log('data：' + JSON.stringify(data))
    // 将上传的excel文件记录到数据库中
    const examRepository = AppDataSource.getRepository(Exam)
    const newExam = examRepository.create({
      authorId: userId,
      title: data.originalFilename,
      fullPath: data.filename,
      downloadUrl: data.fileUrl,
      writerId: userId
    })
    await examRepository.save(newExam)
    success(res, '上传成功', data.fileUrl)
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 获取Excel示例文件下载地址
 */
router.get("/exampleExcel", async function (_req: Request, res: Response) {
  try {
    const excelFileDownloadUrl = getExampleFileDownloadUrl()
    success(res, '获取下载地址成功', excelFileDownloadUrl)
  } catch (error) {
    failure(res, error)
  }
})

export default router